package com.leo;

import javafx.application.Platform;
import javafx.concurrent.Task;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @ClassName MyTask
 * @Description
 * @Author wangss
 * @date 2020.06.18 22:24
 * @Version 1.0
 */
public class MyTask extends Task<Number> {

    @Override
    protected void updateProgress(long workDone, long max) {
        super.updateProgress(workDone, max);
    }

    @Override
    protected void updateProgress(double workDone, double max) {
        super.updateProgress(workDone, max);
    }

    @Override
    protected void updateMessage(String message) {
        super.updateMessage(message);
    }

    @Override
    protected void updateTitle(String title) {
        super.updateTitle(title);
    }

    @Override
    protected void updateValue(Number value) {
        super.updateValue(value);
        System.out.println("是否ui主线程：" + Platform.isFxApplicationThread() + ", " + Thread.currentThread().getName());
        System.out.println(value);
    }

    @Override
    protected Number call() throws Exception {
        System.out.println("是否ui主线程：" + Platform.isFxApplicationThread() + ", " + Thread.currentThread().getName());

        FileInputStream fis = new FileInputStream(new File("D:\\log\\123.jpg"));
        double fileSize = fis.available();
        byte[] bytes = new byte[1024];
        int read = 0;
        double readSize = 0;
        double progress = 0;

        FileOutputStream fos = new FileOutputStream(new File("D:\\log\\2.jpg"));

        this.updateTitle("拷贝");
        while ((read = fis.read(bytes, 0, bytes.length)) != -1) {

            // 预防取消失败的情况
            if (this.isCancelled()) {
                break;
            }

            fos.write(bytes, 0, read);
            readSize = readSize + read;
            progress = readSize / fileSize;

            this.updateProgress(readSize, fileSize);

            if (progress < 0.5) {
                this.updateMessage("请耐心等待");
            } else if (progress < 0.8) {
                this.updateMessage("即将完成");
            } else if (progress < 1) {
                this.updateMessage("就差一步");
            } else if (progress >= 1) {
                this.updateMessage("恭喜完成");
            }

            Thread.sleep(1);
        }

        fis.close();
        fos.close();

        return progress;
    }
}
